package com.diaohaiwen.common.exception;


import com.diaohaiwen.common.enums.StatusCodeEnum;
import com.diaohaiwen.common.obj.Result;

import java.util.function.Supplier;

/**
 * @author 刁海文
 * @since 2023/6/11 16:29
 * @Remark 全局通用异常配置类
 */
public class GlobalException extends RuntimeException {


    /**
     * 状态数据来源{@link StatusCodeEnum#status}
     */
    private final int status;
    /**
     * 消息提示 数据来源{@link StatusCodeEnum#describe}
     */
    private final String msg;

    public GlobalException(int status, String msg) {
        super(msg);
        this.msg = msg;
        this.status = status;
    }

    /**
     * expression 为true时抛出异常
     *
     * @param expression 条件
     * @param status     response 状态码
     * @param message    详细信息
     */
    public static void isTrue(boolean expression, int status, String message) {
        if (expression) {
            throw new GlobalException(status, message);
        }
    }

    /**
     * expression 为false时抛出异常
     *
     * @param expression 条件
     * @param status     response 状态码
     * @param message    详细信息
     */
    public static void isFalse(boolean expression, int status, String message) {
        isTrue(!expression, status, message);
    }

    /**
     * 创建一个异常对象
     *
     * @param message 详细信息
     * @param status  response 状态码
     * @return 异常对象
     */
    public static GlobalException build(int status, String message) {
        return new GlobalException(status, message);
    }

    public static Supplier<GlobalException> supplier(int status, String message) {
        return () -> build(status, message);
    }

    /**
     * 抛出一个异常信息
     *
     * @param status  response 状态码
     * @param message 详细信息
     */
    public static void throwException(int status, String message) {
        throw new GlobalException(status, message);
    }

    public Result<?> getResult() {
        return Result.fail(status, msg);
    }

    public int getStatus() {
        return status;
    }

    public String getMsg() {
        return msg;
    }
}
